package com.jwater.core.serialize;

import java.util.ArrayList;
import java.util.List;

import jwater.org.apache.mina.core.buffer.IoBuffer;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public abstract class AbstractSerialize implements SerializeService {
    /**
     * 序列化数组
     *
     * @param objs
     * @return
     * @throws SerializeException
     */
    @Override
    public byte[] serializeArray(Object... objs) throws SerializeException {
        try {
            if (objs == null || objs.length == 0) {
                return new byte[0];
            }
            List<byte[]> datas = new ArrayList<byte[]>();
            int len = 0;
            for (Object obj : objs) {
                byte[] data = serialize(obj);
                datas.add(data);
                len += data.length;
            }
            IoBuffer buffer = IoBuffer.allocate(len + datas.size() * 4);
            for (byte[] data : datas) {
                buffer.putInt(data.length);
                buffer.put(data);
            }
            return buffer.array();
        } catch (Exception e) {
            throw new SerializeException("serializeArray error", e);
        }
    }

    /**
     * 反序列化数组
     *
     * @param data
     * @return
     * @throws SerializeException
     */
    @Override
    public Object[] deserializeArray(byte[] data) throws SerializeException {
        try {
            if (data == null || data.length == 0) {
                return new Object[0];
            }
            List<Object> list = new ArrayList<Object>();
            IoBuffer buffer = IoBuffer.wrap(data);
            while (buffer.hasRemaining()) {
                int len = buffer.getInt();
                byte[] bytes = new byte[len];
                buffer.get(bytes);
                list.add(deserialize(bytes, null));
            }
            return list.toArray();
        } catch (Exception e) {
            throw new SerializeException("deserializeArray error", e);
        }
    }
}
